/**
 * 工单处理列表
 * @author levy
 * @date    2016/1/10
 * @signForription []
 */
import NoData from "../components/NoData";
import PullRefresh from "../components/mui/PullRefresh";

(function (lf, r) {
    var ajax = lf.utils.ajax,
        log = lf.utils.log,
        flag = ''; //标识,detail页面有用到
    
    
    var imgUrl = '../public/images/taskProcessing/';
    
    var Header = React.createClass({
        componentDidMount: function () {
            var node = r.findDOMNode(this.refs.defaultNode);
            var divs = node.getElementsByTagName('div');
            if (divs.length == 0) return;
            divs[0].style.display = 'block';
            
        },
        clickFn: function (e) {
            var me = this;
            var showActive = function (node) {
                var divs = node.getElementsByTagName('div');
                if (divs.length == 0) return;
                divs[0].style.display = 'block';
                
                //另外两个隐藏
                var header = r.findDOMNode(me.refs.clickHeader);
                var links = header.getElementsByTagName('a');
                for (var i = 0; i < links.length; i++) {
                    if (links[i] != node) {
                        divs = links[i].getElementsByTagName('div');
                        if (divs.length == 0)
                            continue;
                        else {
                            divs[0].style.display = 'none';
                        }
                    }
                }
            };
            
            //a元素被点击
            var node = e.target;
            var type = node.getAttribute('data-type');
            if (!type) {
                //被点击的是p元素,要找到a标签
                var node = e.target.parentNode;
                type = node.getAttribute('data-type');
                type == 1 ? flag = '' : '';// todo 解决type切换再点击进入详情不出现底部按钮
            }
            
            showActive(node);
            this.props.getTaskList(type, 1, false);
        },
        render: function () {
            var data = this.props.data;
            return (
                <div className="item-row" ref="clickHeader">
                    <div className="item">
                        <a ref="defaultNode" onTouchStart={this.clickFn} data-type="1" className="mui-btn">
                            <p>{data.notProcess}</p>
                            <p>待办理</p>
                            <div className="rectangle"></div>
                        </a>
                    </div>
                    <div className="item">
                        <a onTouchStart={this.clickFn} data-type="2" className="mui-btn">
                            <p >{data.flowing}</p>
                            <p>流转中</p>
                            <div className="rectangle"></div>
                        </a>
                    </div>
                    <div className="item">
                        <a onTouchStart={this.clickFn} data-type="3" className="mui-btn">
                            <p >{data.finished}</p>
                            <p>已完成</p>
                            <div className="rectangle"></div>
                        </a>
                    </div>
                </div>
            );
        }
    });
    
    var Task = React.createClass({
        componentDidMount: function () {
            var node = r.findDOMNode(this.refs.tapNode);
            
            //点击事件
            node.addEventListener('tap', function () {
                var detail = 'task-processing-detail.html?orderId=' + this.props.task.orderId
                    + '&staffId=' + liefeng.userInfo.id
                    + '&flag=' + flag;
                lf.bridgeJs.doAction(detail, '工单详情');
            }.bind(this), !1);
        },
        render: function () {
            var task = this.props.task;
            
            //0：未签收；1：已签收 2:退回 3：办结
            var desc = '待签收',
                finishClass = 'ele-hide',
                time = lf.utils.format(task.createTime, 'MM/dd hh:mm');
            if (task.processStatus == '1') {
                desc = '等待处理中...';
            }
            if (task.processStatus == '2') {
                desc = '已退回';
            }
            if (task.processStatus == '3') {
                desc = '已完成';
                finishClass = 'finished';
            }
            
            return (
                <li className="mui-table-view-cell">
                    <a ref="tapNode" className="">
                        <p className="task-title">{task.title}</p>
                        <p>{desc}</p>
                        <span className="time">{time}</span>
                    </a>
                    <div className="task-info" ref="taskInfoNode">
                        <img className={finishClass}
                             src={imgUrl + "finished.png"} alt="finished" width="50" height="50"/>
                        <p className={task.emergency == 1 ? 'urgent' : 'ele-hide'}>
                            紧急
                        </p>
                        <p className={task.serviceType == 1 ? 'paid' : 'ele-hide'}>
                            有偿
                        </p>
                    </div>
                </li>
            );
        }
    });
    
    var TaskList = React.createClass({
        getInitialState: function () {
            return ({
                noData: {
                    span_text: '您还没有处理过工单',
                    btn_text: '去签收',
                    page_url: 'sign-for.html',
                    page_title: '签收',
                },
            });
        },
        componentDidMount: function () {
        },
        render: function () {
            var taskList = this.props.data.map(function (task) {
                return (
                    <Task task={task}/>
                );
            });
            
            if (this.props.total) {
                return (
                    <div ref="taskListNode">
                        {taskList}
                    </div>
                );
            } else {
                return <NoData data={this.state.noData}/>
            }
            
        }
    });
    
    /**
     * props:
     *      page
     */
    var TaskListCon = React.createClass({
        getInitialState: function () {
            return ({
                header: {
                    notProcess: 0,
                    flowing: 0,
                    finished: 0
                },
                taskList: [],
                total: 1,//默认1不显示无数据页面
                loading: {
                    status: ''
                },
                currType: 1, //当前type
            });
        },
        /**
         * @param type 哪种类型的数据
         * @param page 当前页, 默认为 1
         * @param shouldAppend 默认追加, 但 refresh 时传 false
         */
        getTaskList: function (type, page = 1, shouldAppend = true) {
            if (!type || typeof(type ) !== 'string') type = 1;
            
            if (type == 2) {
                flag = lf.taskInfo.FLOWING;
            }
            
            ajax({
                data: {
                    type: type,
                    actor: liefeng.userInfo.id,
                    page: page,
                },
                success: function (data) {
                    let list = this.state.taskList;
                    
                    if (this.state.currType == type && shouldAppend) {
                        list.push(...data.dataList);
                    }
                    else {
                        list = data.dataList;
                        //重置
                        mui('#pullrefresh').pullRefresh().refresh(true);
                    }
                    
                    mui('#pullrefresh')
                    .pullRefresh()
                    .endPullupToRefresh((list.length == data.maxCount)); //refresh completed
                    
                    this.setState({
                        taskList: list,
                        total: list.length,
                        currType: type,
                    });
                }.bind(this),
                error: function (xhr, errorType, error) {
                    console.error('list error');
                }
            }, lf.api.task.list);
        },
        getHeader(user) {
            let me = this;
            ajax({
                data: {
                    actor: user.id
                },
                success: function (resp) {
                    var data = resp.data;
                    me.setState({
                        header: {
                            notProcess: data.waitDealCount || 0,
                            flowing: data.flowingCount || 0,
                            finished: data.completeCount || 0,
                        }
                    });
                },
                error: function () {
                    console.error('header error');
                }
            }, lf.api.listHeader);
        },
        componentWillMount: function () {
            let user = this.props.user;
            
            this.getHeader(user);
            
            //列表默认取待办理
            this.getTaskList(1, 1, false);
            
            lf.appJs.refresh();
            
        },
        componentWillReceiveProps: function (nextProps) {
            this.getTaskList(this.state.currType, nextProps.page, true)
        },
        render: function () {
            return (
                <div className="task-processing">
                    <Header data={this.state.header} getTaskList={this.getTaskList}/>
                    <TaskList data={this.state.taskList} total={this.state.total}/>
                </div>
            );
        }
    });
    
    var Body = r.createClass({
        getInitialState() {
            return {
                page: 1
            }
        },
        pullupFn: function () {
            let newPage = ++this.state.page;
            this.setState({page: newPage});
        },
        render: function () {
            return (
                <PullRefresh data={
                <TaskListCon page={this.state.page} user={this.props.user}/>
                } pullupFn={this.pullupFn}/>
            )
        }
    });
    
    lf.bridgeJs.getUser((user) => {
        r.render(
            <Body user={user}/>,
            document.getElementById('root'), function () {
                $('.mui-scroll').css({background: '#f1f1f1'});
            }
        )
    })
    
})(liefeng, React);
